package com.scau.jansing.thread.first;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Handler;

/**
 *
 * Created by jansing on 2015/12/1.
 */
public class ExceptionThread implements Runnable {
    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("处理未捕获异常： " + t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }

    public static void main(String[] args){
        //也可以用下面这行代码代替工厂
//        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        /**
         * 使用工厂来为每个任务产生特定的线程
         */
        ExecutorService exec = Executors.newCachedThreadPool(
                new HandlerThreadFactory()
        );
        exec.execute(new ExceptionThread());
    }
}

//非常耗时
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("caught " + e);
    }
}

/**
 * 使用工厂为每个线程设置异常处理
 */
class HandlerThreadFactory implements ThreadFactory{
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        return t;
    }
}